/**
 * cookie.js
 * @author Ulyan Sobin
 * @description Cookie tools module
 */

"use strict";

class Cookie {

	/**
	 * `Cookie` constructor
	 * @param {string} key
	 * @param {string} value
	 * @param {Date} expires
	 * @param {string} domain
	 * @param {string} path
	 * @param {boolean} secure
	 * @param {boolean} HttpOnly
	 */
	constructor(key, value, expires, domain, path, secure, HttpOnly) {
		if (!key) throw "Key is necessary for cookie.";
		this.key = key;
		if (!value && value != "") throw "Value is necessary for cookie.";
		this.value = value;
		if (expires) this.expires = expires;
		if (domain) this.domain = domain;
		if (path) this.path = path;
		if (secure) this.secure = secure;
		if (HttpOnly) this.HttpOnly = HttpOnly;
	}

	/**
	 * Stringify `Cookie`
	 * @returns {string}
	 */ 
	stringify() {
		var R = this.key + "=" + this.value;
		if (this.expires) R += ";Expires=" + this.expires.toUTCString();
		if (this.domain) R += ";Domain=" + this.domain;
		if (this.path) R += ";Path=" + this.path;
		if (this.secure) R += ";Secure=" + this.secure;
		if (this.HttpOnly) R += ";HttpOnly";
		return R;
	}
}


class CookieSet {

	constructor() {

	}

	/**
	 * Get an array of cookies' stringify result
	 * @returns {Array<string>}
	 */
	publish() {
		let R = [];
		for (let cookie of this) {
			if (cookie instanceof Cookie)
				R.push(cookie.stringify());
		}
		return R;
	}

	/**
	 * @returns {number}
	 */
	length() {
		return Object.keys(this).length;
	}

	/**
	 * Parse cookies from a string
	 * @param {string} str
	 * @returns {object}
	 */
	static parse(str) {
		let result = {};
		let s = str.trim();
		if (s == "") return result;
		let cookies = s.split(';');
		for (let cookie of cookies) {
			cookie = cookie.trim();
			if (cookie.indexOf('=') == -1) continue; 
			let kvp = cookie.split('=');
			result[kvp[0]] = kvp[1];
		}
		return result;
	}
}


module.exports.Cookie = Cookie;
module.exports.CookieSet = CookieSet;
